import * as React from 'react';
import { DataGrid, GridColDef, GridValueGetterParams } from '@mui/x-data-grid';
import moment from "moment"
const sqlite3 = window.require('sqlite3').verbose();
console.log(sqlite3)
let constr=`./data.db`
let conn = new sqlite3.Database(constr);
let option_values=["","3.36","1.31","0.083"]
console.log(conn)
const minuteJ1=(id1)=>{
    let d2=moment(id1,"YYYY-MM-DD HH:mm")
    d2.add(1,"minutes")
    return d2.format("YYYY-MM-DD HH:mm");//"%04d-%02d-%02d %02d:%02d" % (d2.year,d2.month,d2.day,d2.hour,d2.minute)
}
const deleteRow=(row)=>{
    let id1=row.SampleId
    conn.run(`delete from  result where sampleid='${id1}'`)
}
const copyRow=(src,dest)=>{
    // let id1=row.SampleId
    // conn.run(`delete from  result where sampleid='${id1}'`)
}
function delOne2(id2){
    let id1=minuteJ1(id2)
    console.log(id2);
    console.log(id1);
    let cmd=`select * from result where sampleid>='${id2}' and sampleid<'${id1}'` ;
    console.log(cmd);
    conn.each(cmd,(err, row)=>{
        if(err!==null){
            console.log(err);
        }else{
            deleteRow(conn,row)
        }
        return;
    });
}
function dayend(s){//'2016-12-23 14:59'    
    s=s.split(" ")[0]
    s=s+" 23:59"
    return s
}
function delOne2(id2){
    let id1=minuteJ1(id2)
    console.log(id2);
    console.log(id1);
    let cmd=`select * from result where sampleid>='${id2}' and sampleid<'${id1}'` ;
    console.log(cmd);
    conn.each(cmd,(err, row)=>{
        if(err!==null){
            console.log(err);
        }else{
            deleteRow(conn,row)
        }
        return;
    });
}
function dayend(s){//'2016-12-23 14:59'    
    s=s.split(" ")[0]
    s=s+" 23:59"
    return s
}
function upRow(row,wtb){
  treatRow(row,1/1.005)
}
function downRow(row){
  treatRow(row,1.005) 
}
function treatRow(row,wtb){
    // console.log(row);
    let id1=row.SampleId
    let oldwt=row.SampleWeight
    let wt=oldwt*wtb
    let old01=row.Content01
    let old02=row.Content02
    // let old03=row.Content03
    // console.log(oldwt,old01,old02,old03)
    let new01=old01/wtb
    let new02=old02/wtb
    // let new03=0;
    // if (old03) new03=old03/wtb;
    row.SampleWeight=wt
    row.Content01=new01
    row.Content02=new02
    // row.Content03=new03
    conn.run(`update result set sampleweight=${wt},Content01=${new01},Content02=${new02} where sampleid='${id1}'`
        ,(err,row)=>{
            if(err!==null){
                console.log(err);
            }else{
                console.log("ok");
            }
            return;

        })
}
export default function DataTable() {
  const [state,setState]=React.useState({
    rows:[],columns:[],days:1,months:1
    ,src:null
    ,use_days:true,name:"",option:"3.36"})
  React.useEffect(()=>{
    loadData(state.days,state.months,state.use_days);
  },[])
  const [selectionModel, setSelectionModel] = React.useState<GridSelectionModel>([]);
  const loadData=(days,months,use_days,name)=>{
    if(name===undefined) name=""
    console.log("loadData==============")
    console.log(days,months,use_days)
    de=moment();
    
    de.hour(23)
    de.minute(59)
    de.second(59)
    window.de=de
    console.log(de)
    // de.setTime(QTime(23,59,59));

    // // ui.dateTimeEdit_begin->setDateTime(db);
    let de_str=de.format("YYYY-MM-DD HH:mm:ss");//toString("yyyy-MM-dd hh:mm:ss");
    // console.log(de_str);
    // console.log(days)
    let db;
    if (use_days){
      db=de.add(-days, 'days');
    }else{
      db=de.add(-months, 'months');
    }
    // console.log(db)
    // db.setTime(QTime(0,0,0));
    let db_str=db.format("YYYY-MM-DD HH:mm:ss");
    console.log(db_str,de_str)
    // // ui.dateTimeEdit_end->setDateTime(de);
    // qDebug()<<db_str;
    // qDebug()<<de_str;
    // model->setQuery("select * from result where SampleId between '"+db_str+"' and '"+de_str+"'");
    let columns=[];

    let cmd="select SampleId,SampleName,SampleNum,SampleWeight,Content01,Content02 from result where SampleName like '%"+name+"%' and SampleId between '"+db_str+"' and '"+de_str+"'"
    console.log(cmd);
    conn.all(cmd,(err,rows)=>{
      console.log("all")
      console.log(err,rows)
      if(err){
        console.log(err);
      }else{
        for(f in rows[0]){
          // console.log(f)
          if (f==="SampleId"){
            columns.push({field:f,width:160});
          }else{
            columns.push({field:f,width:100});
          }
        }
        for(var i=0;i<rows.length;i++){
          rows[i].id=i;
        }
        setState((state)=>({...state,rows:rows,columns:columns}));
      }
    })
  }
  let style_days,setyle_months;
  if(state.use_days){
    style_days={backgroundColor:"#88f",width:"30px"}
    setyle_months={backgroundColor:"#fff",width:"30px"}
  }else{
    style_days={backgroundColor:"#fff",width:"30px"}
    setyle_months={backgroundColor:"#88f",width:"30px"}
  }
  console.log(state);
  let options=[]
  for (var i=0;i<option_values.length;i++) {
      options.push(
        <option key={i}>{option_values[i]}</option>
      );
  }
  return (
    <div style={{ height: 800, width: '100%' }}>
    <div>
    <input value={state.name} onKeyPress={(e)=>{
        if (e.which !== 13) return;
        loadData(state.days,state.months,state.use_days,state.name);
      }} onFocus={()=>{
        // setState((state)=>({...state,use_days:true}));
      }} onChange={(e)=>{
        setState((state)=>({...state,name:e.target.value}));
      }}></input>name
      <button onClick={()=>{
        loadData(state.days,state.months,state.use_days,state.name);
      }}>load</button>
      <button onClick={()=>{
        let new_rows=state.rows;
        for(var i=0;i<selectionModel.length;i++){
          let row=state.rows[selectionModel[i]]
          upRow(row)
          new_rows[i]=row;
        }
        setState((state)=>({...state,rows:new_rows}));
      }}>+</button>
      <button onClick={()=>{
       let new_rows=state.rows;
       for(var i=0;i<selectionModel.length;i++){
          let row=state.rows[selectionModel[i]]
          downRow(row)
          new_rows[i]=row;
          
        }
        setState((state)=>({...state,rows:new_rows}));
      }}>-</button>
      <button onClick={()=>{
       let new_rows=[];
       for(var i=0;i<selectionModel.length;i++){
          let row=state.rows[selectionModel[i]]
          deleteRow(row)
        }
        for(var i=0;i<state.rows.length;i++){
          let is_select=false;
          for(var j=0;j<selectionModel.length;j++){
            if(i===selectionModel[j]){
              is_select=true
              break;
            }
          }
          if(is_select){
          }else{
            new_rows.push(state.rows[i])
          }
        }
        console.log(state.rows.length)
        console.log(new_rows.length)
        setState((state)=>({...state,rows:new_rows}));
      }}>delete</button>
      <input style={style_days} value={state.days} onKeyPress={(e)=>{
        if (e.which !== 13) return;
        loadData(state.days,state.months,state.use_days,state.name);
      }} onFocus={()=>{
        setState((state)=>({...state,use_days:true}));
      }} onChange={(e)=>{
        setState((state)=>({...state,days:e.target.value,use_days:true}));
      }}></input>days
      <input style={setyle_months} value={state.months} onKeyPress={(e)=>{
        if (e.which !== 13) return;
        loadData(state.days,state.months,state.use_days,state.name);
      }}  
      onFocus={()=>{
        setState((state)=>({...state,use_days:false}));
      }} 
      onChange={(e)=>{
        setState((state)=>({...state,months:e.target.value,use_days:false}));
      }}></input>months
      </div>
      <div>
        <select value={state.option}
          onChange={(e)=>{
            console.log(e);
            setState((state)=>({...state,option:e.target.value}));
          }}
        >{options}
        </select>
        <button>rename</button>
        <button onClick={()=>{
          for(var i=0;i<selectionModel.length;i++){
            let row=state.rows[selectionModel[i]]
            setState((state)=>({...state,src:row.SampleId}));
            break;
          }
        }}>copy</button>
        <button onClick={()=>{
          if(state.src===null) return;
          let dest_row;
          for(var i=0;i<selectionModel.length;i++){
            let dest_row=state.rows[selectionModel[i]]
            break;
          }
          copy(state.src,dest_row);
        }}>paste</button>
      </div>
      <DataGrid 
        rows={state.rows}
        columns={state.columns}
        pageSize={13}
        rowsPerPageOptions={[13]}
        checkboxSelection
        onSelectionModelChange={(newSelectionModel) => {
          console.log("onSelectionModelChange")
          setSelectionModel(newSelectionModel);
          console.log(newSelectionModel)
        }}
        selectionModel={selectionModel}
      />
    </div>
  );
}

// import * as React from 'react';
// import { DataGrid, GridRowsProp, GridColDef } from '@mui/x-data-grid';

// const rows: GridRowsProp = [
//   { id: 1, col1: 'Hello', col2: 'World' },
//   { id: 2, col1: 'DataGridPro', col2: 'is Awesome' },
//   { id: 3, col1: 'MUI', col2: 'is Amazing' },
// ];

// const columns: GridColDef[] = [
//   { field: 'col1', headerName: 'Column 1', width: 150 },
//   { field: 'col2', headerName: 'Column 2', width: 150 },
// ];

// export default function App() {
//   return (
//     <div style={{ height: 300, width: '100%' }}>
//       <DataGrid rows={rows} columns={columns} />
//     </div>
//   );
// }

